﻿using Microsoft.Owin.Security;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SuperJoe.Framwork.Web
{
    public static class IdentityManager
    {

        public static string ClaimTypeUser { get; set; }
        public static string CookieName { get; set; }

        public static void SignIn(IdentityUser userObject, DateTime? expireTime = null)
        {

            var claimIdentity = new ClaimsIdentity(CookieName);
            claimIdentity.AddClaim(new Claim(ClaimTypeUser, JsonConvert.SerializeObject(userObject)));

            var authenProp = new AuthenticationProperties();
            if (expireTime != null)
            {
                authenProp.ExpiresUtc = expireTime.Value.ToUniversalTime();
                authenProp.IsPersistent = true;
            }


            Authentication.SignIn(authenProp, claimIdentity);
        }

        private static IAuthenticationManager Authentication
        {
            get
            {
                return HttpContext.Current.GetOwinContext().Authentication;
            }
        }

        public static void SignOut()
        {
            Authentication.SignOut(CookieName);
        }

        public static bool IsAuthenticated
        {
            get
            {
                return HttpContext.Current.User != null
                    && HttpContext.Current.User.Identity != null
                    && HttpContext.Current.User.Identity.IsAuthenticated;
            }
        }

        public static IdentityUser GetUser()
        {

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var claim = ((ClaimsPrincipal)HttpContext.Current.User).Claims.SingleOrDefault(c => c.Type == ClaimTypeUser);
                if (claim != null)
                {
                    return JsonConvert.DeserializeObject<IdentityUser>(claim.Value);
                }
            }

            return null;

        }
    }
}
